package com.yvon.im.processor;

import cn.hutool.json.JSONUtil;
import com.yvon.im.message.ResponseMessage;
import com.yvon.im.message.SendToUserMessage;
import com.yvon.im.session.Session;
import com.yvon.im.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author : wangyufeng
 * @since : 2021-12-02
 */
public class SendToUserProcessor extends Processor<SendToUserMessage> {

    @Override
    public void exec(Channel channel, String msg) {
        SendToUserMessage message = parse(msg);
        if (Objects.nonNull(message)) {
            String receiver = message.getReceiver();
            String content = message.getContent();
            Session session = SessionUtil.getSession(channel);
            ResponseMessage responseMessage = new ResponseMessage(session.getUsername(), LocalDateTime.now(), content);

            Channel channel1 = SessionUtil.getChannel(receiver);
            if (channel1.isActive()) {
                channel1.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(responseMessage)));
            }
        }
    }
}
